package yang.itcode.controller;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yang.itcode.model.Result;
import yang.itcode.service.CustomerService;

import static yang.itcode.constant.ErrorConstant.*;

@RestController
@RequestMapping("/api/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @PostMapping
    public Result<Object> addCustomer(@RequestBody JSONObject obj) {
        if (customerService.addCustomer(obj)) {
            return Result.success();
        } else {
            return Result.error(CUSTOMER_ADD_EXCEPTION_CODE, CUSTOMER_ADD_EXCEPTION_MESSAGE);
        }
    }

    @PostMapping("/list")
    public Result<PageInfo<JSONObject>> getCustomerList(@RequestBody JSONObject obj) {
        Integer pageNum = obj.getInt("pageNum");
        Integer pageSize = obj.getInt("pageSize");
        JSONObject condition = obj.getJSONObject("condition");
        return Result.success(customerService.getCustomerList(pageNum, pageSize, condition));
    }

    @GetMapping("/{id}")
    public Result<JSONObject> getCustomerDetail(@PathVariable("id") Integer id) {
        return Result.success(customerService.getCustomerDetail(id));
    }

    @PutMapping
    public Result<Object> updateCustomer(@RequestBody JSONObject obj) {
        if (customerService.updateCustomer(obj)) {
            return Result.success();
        } else {
            return Result.error(CUSTOMER_UPDATE_EXCEPTION_CODE, CUSTOMER_UPDATE_EXCEPTION_MESSAGE);
        }
    }

    @DeleteMapping("/{id}")
    public Result<Object> deleteCustomer(@PathVariable("id") Integer id) {
        if (customerService.deleteCustomer(id)) {
            return Result.success();
        } else {
            return Result.error(CUSTOMER_DELETE_EXCEPTION_CODE, CUSTOMER_DELETE_EXCEPTION_MESSAGE);
        }
    }
}
